<?php

/**
 *    买家退货退款管理控制器
 *
 *    @author   yanghj 2014-08-1
 *    @usage    none
 */
class Buyer_returnsApp extends MemberbaseApp
{
    var $_order_mod;
    var $_order_extm_mod; 
	var $_order_goods_mod;
	var $_order_log_mod;
	var $_returns_mod;
    var $_returns_log_mod;
    var $_user_safety_mod;
    var $_address_mod;
    var $valid_time;
    var $interval;
    var $confirm_time;

    /* 构造函数 */
    function __construct()
    {
         $this->Buyer_returnsApp();
    }

    function Buyer_returnsApp()
    {
        parent::__construct();

        $this->_order_mod =& m('order');
        $this->_order_extm_mod =& m('orderextm');
		$this->_order_goods_mod =& m('ordergoods');
		$this->_order_log_mod =& m('orderlog');
		$this->_returns_mod =& m('returns');
        $this->_returns_log_mod =& m('returnslog');
        $this->_user_safety_mod =& m('usersafety');
        $this->_address_mod =& m('selleraddress');
        $this->valid_time = gmtime()-7*3600*24;
        $this->interval = 5 * 24 * 3600 ;//默认15天
        $this->confirm_time = 10 * 24 * 3600 ;//默认10天
    }
	function index()
	{
	   
		/* 获取订单中符合退货退款列表 */
		$this->_get_returns();

		$this->_curlocal(LANG::get('member_center'), 'index.php?app=member',
		LANG::get('my_sales_return'), 'index.php?app=buyer_returns','退货退款申请');

		/* 当前用户中心菜单 */
		$this->_curitem('my_sales_return');
		$this->_curmenu('returns_list');
		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_sales_return'));
		$this->display('buyer_returns.index.html');
	}
    
    
    /**
     *    退货退款记录
     *    @author    yanghj 2014.8.5
     */
    function record()
	{
	    if(isset($_GET['returns_type']) && intval($_GET['returns_type'])>0 && intval($_GET['returns_type'])<5)
        {
            $returns_type = intval($_GET['returns_type']);
        }
        else
        {
             $returns_type = 2;
        }
        $cfg_returns = $this->_get_cfg_msg();
	    $page = $this->_get_page(10);
		$returns = $this->_returns_mod->find(array(
		'fields'        => "this.returns_sn, this.type, this.status, this.add_time, this.returns_amount, order.order_id, order.order_sn, order.status as order_status,ordergoods.goods_id,ordergoods.goods_name,ordergoods.specification,ordergoods.quantity as goods_quantity",
		'conditions'    => " returns.type = {$returns_type} AND returns.buyer_id=" . $this->visitor->get('user_id'),
		'join'          => 'belongs_to_order,belongs_to_ordergoods',
        'order'         => 'returns_id DESC',
        'count'         => true,
		'limit'         => $page['limit'],
		));
        if($returns)
        {
            foreach($returns as $key => $val)
            {
                $returns[$key]['returns_status'] = $cfg_returns['status'][$val['status']][$val['type']]['msg_1'];//退货退款状态提示
            }
            
        }
        //var_dump($returns);

		$this->_curlocal(LANG::get('member_center'), 'index.php?app=member',
		LANG::get('my_sales_return'), 'index.php?app=buyer_returns','退货/退款列表');

		/* 当前用户中心菜单 */
		$this->_curitem('my_sales_return');
		$this->_curmenu('returns_list');
		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_sales_return'));
        
        $page['item_count'] = $this->_returns_mod->getCount();
        $this->_format_page($page);
		$this->assign('returns_list', $returns);	
        $this->assign('returns_type', $returns_type);		
		$this->assign('page_info', $page);
		$this->display('buyer_returns.record.html');
	}
    
    /**
     *    申请退货退款
     *    @author    yanghj 2014.8.5
     */
    function add()
	{
	    $rec_id = isset($_GET['rec_id']) ? intval($_GET['rec_id']) : 0;
        if(!$rec_id)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }
        $cfg_returns = $this->_get_cfg_msg(); 
        $goods_data = $this->_order_goods_mod->get(array(
    		'fields'        => "this.order_id,this.goods_id,this.goods_name,this.specification,this.goods_image,this.price,this.quantity,order.status,order.finished_time,order.goods_amount,order.seller_id,order.buyer_id,order.order_amount",
    		'conditions'    => "rec_id={$rec_id} AND buyer_id=" . $this->visitor->get('user_id'),
    		'join'          => 'belongs_to_order',
    		));
         /*判断商品是否合适申请记录*/ 
        if(!$goods_data || !in_array($goods_data['status'],array(ORDER_ACCEPTED,ORDER_SHIPPED,ORDER_EVALUA,ORDER_FINISHED)) || ($goods_data['finished_time'] < $this->valid_time && $goods_data['finished_time'] != 0))
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }
        /*判断是否有申请记录*/
        $returns_data = $this->_returns_mod->get(array(
		'fields'        => "returns_id",
		'conditions'    => "order_id={$goods_data['order_id']} AND rec_id={$goods_data['rec_id']} AND status !=2 AND status !=-1 AND  buyer_id=" . $this->visitor->get('user_id'),
		));
        if($returns_data)
        {  
            //如果有就跳转到详细页面
            header("Location:index.php?app=buyer_returns&act=view&returns_id=".$returns_data['returns_id']);
			return;           
        }    
        /*计算需退运费,如果为0则卖家承担运费*/
        $returns_fee = 0.00 ;
        $order_extm_data = $this->_order_extm_mod->get(array(
            'fields'        => "shipping_fee,free_shipping",
            'conditions'    => "order_id={$goods_data['order_id']} ",
        ));
        $shipping_fee = floatval($order_extm_data['shipping_fee']);
        $free_shipping = floatval($order_extm_data['free_shipping']);

        if($shipping_fee>0)
        {
            $returns_record = $this->_returns_mod->getRow("SELECT SUM(shipping_fee) as sum_shipping_fee, SUM(goods_amount) as sum_goods_amount FROM {$this->_returns_mod->table} WHERE order_id={$goods_data['order_id']} AND status NOT IN(0,2,-1)  AND  buyer_id=" . $this->visitor->get('user_id'));
            $returns_shipping_fee = floatval($returns_record['sum_shipping_fee']);//已退的运费
            $returns_fee = sprintf("%.2f",$shipping_fee - $free_shipping - floatval($returns_shipping_fee));
        }
        $returns_goods_amount = sprintf("%.2f",$goods_data['order_amount'] - floatval($returns_record['sum_goods_amount']) - $shipping_fee - $free_shipping);//还可以退的商品金额
        $goods_data['returns_fee'] = $returns_fee;//需退运费
        $goods_data['order_goods_amount'] = $goods_data['price'] * $goods_data['quantity'] > $returns_goods_amount ? $returns_goods_amount : number_format($goods_data['price'] * $goods_data['quantity'],2);
	    if (!IS_POST)
		{           
            $tpl = 'buyer_returns.add.html';                      
            
            /*选择退款类型后*/
            if(isset($_GET['returns_type']) && intval($_GET['returns_type'])>0 && intval($_GET['returns_type'])<5)
            {
                $returns_type = intval($_GET['returns_type']);
                $tpl = 'buyer_returns.from.html';               
                $this->import_resource(array(
    			'script' => 'jquery.plugins/jquery.validate.js,jquery.plugins/additional-methods.js',
    			));
                $this->assign('returns_reason',$cfg_returns['reason']);//退货退款原因                
            }
            if($goods_data['finished_time'] >= gmtime()-7*3600*24)
            {
                $goods_data['finished_type'] = 1;//买家已确认收货（7天内）
            }
            else if($goods_data['finished_time'] >= gmtime()-15*3600*24 && $goods_data['finished_time'] < gmtime()-7*3600*24)
            {
                $goods_data['finished_type'] = 2;//买家已确认收货（15天内）
            }
            else
            {
                $goods_data['finished_type'] = 0;
            }
                        
    		$this->_curlocal(LANG::get('member_center'), 'index.php?app=member',
    		LANG::get('my_sales_return'), 'index.php?app=buyer_returns','退货/退款申请');
    
    		/* 当前用户中心菜单 */
    		$this->_curitem('my_sales_return');
    		$this->_curmenu('returns_list');
    		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_sales_return'));
            $this->assign('goods',$goods_data);
            $this->assign('rec_id',$rec_id);
            $this->assign('returns_type',$returns_type);
    		$this->display($tpl);		  
		}
        else
        {
            if(isset($_GET['returns_type']) && intval($_GET['returns_type'])>0 && intval($_GET['returns_type'])<5)
            {
                $returns_type = intval($_GET['returns_type']);
                $refund_type = intval($_GET['refund_type'])>0 ? 1 : 0;
                if(floatval($_POST['goodsMoney']) > $goods_data['order_goods_amount'] || floatval($_POST['goodsFreight']) > $goods_data['returns_fee'] || empty($_POST['reason']) || (empty($_POST['goodsMoney']) && empty($_POST['goodsFreight'])))
                {
                     $this->show_warning('提交申请的数据不正确,请重新填写!');
			         return;
                }
                $upload_img = $this->_uploadify_img();
                if($upload_img['state'] === false )
                {
                     $this->show_warning($upload_img['msg']);
			         return;                    
                }
                $user_mod =& m('member');
                $seller_name = $user_mod->get_fields_name($goods_data['seller_id'],'user_name');
                $data = array(
    			'returns_sn' => $this->_get_returns_code(),
    			'order_id'    => (int)$goods_data['order_id'],
    			'rec_id'     => (int)$goods_data['rec_id'],
    			'type'   =>  $returns_type,
    			'refund_type'   =>  $refund_type,
    			'seller_id'   => (int)$goods_data['seller_id'],
    			'buyer_id'   => (int)$goods_data['buyer_id'],
                'returns_seller_name'   =>  $seller_name,
    			'returns_buyer_name'   => $this->visitor->get('user_name'),
    			'status'   => 1,
                'add_time'   => gmtime(),
                'goods_amount'   => floatval($_POST['goodsMoney']),
    			'shipping_fee'   => floatval($_POST['goodsFreight']),
    			'returns_amount'   => floatval($_POST['goodsMoney']) + floatval($_POST['goodsFreight']),
                'quantity'   => $refund_type == 1 ? 0 : floor(floatval($_POST['goodsMoney'])/$goods_data['price']),
                'returns_reason'   => html_script($_POST['reason']),
                'returns_explain'   => html_script($_POST['message']),
                'returns_img'   => !empty($upload_img['file_url']) ? implode('|',$upload_img['file_url']) : '',
    			);

                //当只退运费的时候,退商品数量默认为0
                if(empty($data['goods_amount']) && $data['shipping_fee'])
                {
                    $data['quantity'] = 0 ;
                }
                
                /*添加到退货退款表*/
                if (!($returns_id = $this->_returns_mod->add($data)))
                {
                    $this->show_warning($this->_returns_mod->get_error());    
                    return;
                }
                $remark = floatval($_POST['goodsFreight']) == 0 ? $cfg_returns['status']['1'][$returns_type]['msg_3'] . '退商品金额：'.floatval($_POST['goodsMoney']).'元' : $cfg_returns['status']['1'][$returns_type]['msg_3'] . '退商品金额：' . floatval($_POST['goodsMoney']) . '元，退运费金额：' . floatval($_POST['goodsFreight']).'元';
                $log_data = array(
    			'returns_id' => $returns_id,
    			'operator'   => $this->visitor->get('user_name'),
    			'remark'     => $remark,
                'log_time'   => gmtime(),
    			);
                
                /*添加到退货退款日志表*/
                if (!($this->_returns_log_mod->add($log_data)))
                {
                    $this->show_warning($this->_returns_log_mod->get_error());    
                    return;
                }
                $this->_returns_mod->send_returns_email($goods_data['seller_id'],$returns_id,1);//发送邮件给卖家;
                
                //跳转到详细页面
                $this->show_message('操作成功!','查看详细','index.php?app=buyer_returns&act=view&returns_id='.$returns_id);
		    	return;                 
                                           
            }
            else
            {
                $this->show_warning('failure_error','back_index', 'index.php');
			    return;               
            }            
        }
	    
	}
    
    /**
     *    修改退货退款记录
     *    @author    yanghj 2014.8.6
     */
    function edit()
	{
	    $returns_id= isset($_GET['returns_id']) ? intval($_GET['returns_id']) : 0;
        if(!$returns_id)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }
        $cfg_returns = $this->_get_cfg_msg(); 
        $returns_info = $this->_returns_mod->get(array(
		'fields'        => "this.*, order.order_sn, order.status as order_status,order.order_amount,order.goods_amount as o_goods_amount,ordergoods.goods_id,ordergoods.goods_name,ordergoods.specification,ordergoods.goods_image,ordergoods.price,ordergoods.quantity as goods_quantity",
		'conditions'    => "returns_id={$returns_id} AND returns.buyer_id=" . $this->visitor->get('user_id'),
		'join'          => 'belongs_to_order,belongs_to_ordergoods',
		)); 
        if(!$returns_info)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }  
        /*计算需退运费,如果为0则卖家承担运费*/
        $returns_fee = 0.00 ;
        $order_extm_data = $this->_order_extm_mod->get(array(
            'fields'        => "shipping_fee,free_shipping",
            'conditions'    => "order_id={$returns_info['order_id']} ",
        ));
        $shipping_fee = floatval($order_extm_data['shipping_fee']);
        $free_shipping = floatval($order_extm_data['free_shipping']);

        if($shipping_fee>0)
        {
            $returns_record = $this->_returns_mod->getRow("SELECT SUM(shipping_fee) as sum_shipping_fee, SUM(goods_amount) as sum_goods_amount  FROM {$this->_returns_mod->table} WHERE order_id={$returns_info['order_id']} AND status NOT IN(0,2,-1) AND returns_id !={$returns_id} AND  buyer_id=" . $this->visitor->get('user_id'));
            $returns_shipping_fee = floatval($returns_record['sum_shipping_fee']);//已退的运费
            $returns_fee = sprintf("%.2f",$shipping_fee - $free_shipping - floatval($returns_shipping_fee));
        }

        $returns_goods_amount = sprintf("%.2f",$returns_info['order_amount'] - floatval($returns_record['sum_goods_amount']) - $shipping_fee - $free_shipping);//还可以退的商品金额
        $returns_info['returns_fee'] = $returns_fee;//需退运费
        $returns_info['order_goods_amount'] = $returns_info['price'] * $returns_info['goods_quantity'] > $returns_goods_amount ? $returns_goods_amount : sprintf("%.2f",$returns_info['price'] * $returns_info['quantity']);

        $returns_info['order_goods_amount'] = $returns_info['goods_amount'] > $returns_goods_amount || $returns_info['goods_amount'] == 0 ? $returns_goods_amount : $returns_info['goods_amount'];
	    if (!IS_POST)
		{           
 
            $this->import_resource(array(
    			'script' => 'jquery.plugins/jquery.validate.js,jquery.plugins/additional-methods.js',
    			));
    		$this->_curlocal(LANG::get('member_center'), 'index.php?app=member',
    		LANG::get('my_sales_return'), 'index.php?app=buyer_returns','退货/退款修改');
    
    		/* 当前用户中心菜单 */
    		$this->_curitem('my_sales_return');
    		$this->_curmenu('returns_list');
    		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_sales_return'));
            $this->assign('returns',$returns_info);
            $this->assign('returns_reason',$cfg_returns['reason']);//退货退款原因
    		$this->display('buyer_returns.edit.html');		  
		}
        else
        {
            
            
            if(floatval($_POST['goodsMoney']) > $returns_info['order_goods_amount'] || floatval($_POST['goodsFreight']) > $returns_info['returns_fee'] || empty($_POST['reason']) || (empty($_POST['goodsMoney']) && empty($_POST['goodsFreight'])))
            {
                 $this->show_warning('提交申请的数据不正确,请重新填写!');
		         return;
            }
            $upload_img = $this->_uploadify_img();
            if($upload_img['state'] === false )
            {
                 $this->show_warning($upload_img['msg']);
		         return;                    
            }
            $data = array(
			'status'   => 1,
            'add_time'   => gmtime(),
            'goods_amount'   => floatval($_POST['goodsMoney']),
			'shipping_fee'   => floatval($_POST['goodsFreight']),
			'returns_amount'   => floatval($_POST['goodsMoney']) + floatval($_POST['goodsFreight']),
            'quantity'   => $returns_info['refund_type'] == 1 ? 0 : floor(floatval($_POST['goodsMoney'])/$returns_info['price']),
            'returns_reason'   => html_script($_POST['reason']),
            'returns_explain'   => html_script($_POST['message']),
            'returns_img'   => !empty($upload_img['file_url']) ? implode('|',$upload_img['file_url']) : '',
			);

            //当只退运费的时候,退商品数量默认为0
            if(empty($data['goods_amount']) && $data['shipping_fee'])
            {
                $data['quantity'] = 0 ;
            }
            
            /*修改退货退款状态*/
            $this->_returns_mod->edit($returns_id, $data);
            if ($this->_returns_mod->has_error())
    		{
    			$this->show_warning($this->_returns_mod->get_error());
    			return;
    		}
            if($returns_info['returns_img'])
            {
                $this->_delete_uploadify_img($returns_info['returns_img']); //删除申请上传的图片                
            }
            
            if($returns_info['refuse_img'])
            {
                $this->_delete_uploadify_img($returns_info['refuse_img']); //删除卖家拒绝上传的图片                
            }
            
            $remark = floatval($_POST['goodsFreight']) == 0 ? '买家修改'.$cfg_returns['type'][$returns_info['type']].'申请。退商品金额：'.floatval($_POST['goodsMoney']).'元' : '买家修改'.$cfg_returns['type'][$returns_info['type']].'申请。退商品金额：' . floatval($_POST['goodsMoney']) . '元，退运费金额：' . floatval($_POST['goodsFreight']).'元';
                
            $log_data = array(
			'returns_id' => $returns_id,
			'operator'   => $this->visitor->get('user_name'),
			'remark'     => $remark,
            'log_time'   => gmtime(),
			);
            
            /*添加到退货退款日志表*/
            if (!($this->_returns_log_mod->add($log_data)))
            {
                $this->show_warning($this->_returns_log_mod->get_error());    
                return;
            }
            $this->_returns_mod->send_returns_email($returns_info['seller_id'],$returns_id,2);//发送邮件给卖家;
            
            $this->show_message('操作成功!','查看详细','index.php?app=buyer_returns&act=view&returns_id='.$returns_id);
	    	return;                                       
        }
	    
	}
    
    
    /**
     *    取消退货退款记录
     *    @author    yanghj 2014.8.6
     */
    function cancel()
	{
	    $returns_id = isset($_GET['returns_id']) ? intval($_GET['returns_id']) : 0;
        if(!$returns_id)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }
        $returns_data = $this->_returns_mod->get(array(
		'fields'        => "this.returns_id,this.type,order.status",
		'conditions'    => "returns_id={$returns_id} AND  returns.buyer_id=" . $this->visitor->get('user_id'),
        'join'          => 'belongs_to_order',
		));
        if(!$returns_data)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }
        
        $cfg_returns = $this->_get_cfg_msg();
        if($returns_data['status'] == 40 || $returns_data['status'] == 50 )
        {
            $data = array(
    		'status'    => 0,
            'finished_time'   => gmtime(),
    		);
            
        } 
        else
        {
            $data = array(
    		'status'    => 2,
            'finished_time'   => gmtime(),
    		);
        }     
	    
        
        /*修改退货退款状态*/
        $this->_returns_mod->edit($returns_id, $data);
        if ($this->_returns_mod->has_error())
		{
			$this->show_warning($this->_returns_mod->get_error());
			return;
		}                        
        $log_data = array(
		'returns_id' => $returns_id,
		'operator'   => $this->visitor->get('user_name'),
		'remark'     => $cfg_returns['status']['2'][$returns_data['type']]['msg_3'],
        'log_time'   => gmtime(),
		);
        
        /*添加到退货退款日志表*/
        if (!($this->_returns_log_mod->add($log_data)))
        {
            $this->show_warning($this->_returns_log_mod->get_error());    
            return;
        }
        $this->show_message('操作成功!','查看详细','index.php?app=buyer_returns&act=view&returns_id='.$returns_id);
	}
    
    /**
     *    卖家同意退货退款后,买家提交退货物流信息
     *    @author    yanghj 2014.8.6
     */
    function logistics()
	{

	    $returns_id = isset($_GET['returns_id']) ? intval($_GET['returns_id']) : 0;
        if(!$returns_id)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }
        $returns_data = $this->_returns_mod->get(array(
		'fields'        => "status,type,seller_id",
		'conditions'    => "returns_id={$returns_id} AND  buyer_id=" . $this->visitor->get('user_id'),
		));
        if(!$returns_data || $returns_data['status'] != 3)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }
        if(empty($_POST['express']) || empty($_POST['expressNum']) || empty($_POST['message']))
        {
             $this->show_warning('提交的数据不正确,请重新填写!');
	         return;
        }
    
	    $data = array(
		'status'    => 5,
        'shipping_time'   => gmtime(),
        'shipping_name'   => empty($_POST['otherExpress'])? html_script($_POST['express']) : html_script($_POST['otherExpress']),  
        'shipping_sn'   => html_script($_POST['expressNum']), 
        'shipping_msg'   => html_script($_POST['message']),      
		);
        
        /*修改退货退款状态*/
        $this->_returns_mod->edit($returns_id, $data);
        if ($this->_returns_mod->has_error())
		{
			$this->show_warning($this->_returns_mod->get_error());
			return;
		}                        
        $log_data = array(
		'returns_id' => $returns_id,
		'operator'   => $this->visitor->get('user_name'),
		'remark'     => '买家已退货，物流公司：'.$data['shipping_name'].'，物流单号：'.$data['shipping_sn'].'。留言:'.$data['shipping_msg'],
        'log_time'   => gmtime(),
		);
        
        /*添加到退货退款日志表*/
        if (!($this->_returns_log_mod->add($log_data)))
        {
            $this->show_warning($this->_returns_log_mod->get_error());    
            return;
        }
        $this->_returns_mod->send_returns_email($returns_data['seller_id'],$returns_id,3);//发送邮件给卖家;
        
        $this->show_message('操作成功!','查看详细','index.php?app=buyer_returns&act=view&returns_id='.$returns_id);
	}



	/**
     *    查看详情
     *    @author    yanghj 2014.8.1
     */
	function view()
	{
		$returns_id = isset($_GET['returns_id']) ? intval($_GET['returns_id']) : 0;
        if(!$returns_id)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }
        
        $left_time = 0;//倒计时间,以秒为单位
        $cfg_returns = $this->_get_cfg_msg(); 
		$returns_info = $this->_returns_mod->get(array(
		'fields'        => "this.*, order.order_sn, order.status as order_status,ordergoods.goods_id,ordergoods.goods_name,ordergoods.specification,ordergoods.goods_image,ordergoods.price,ordergoods.quantity as goods_quantity",
		'conditions'    => "returns_id={$returns_id} AND returns.buyer_id=" . $this->visitor->get('user_id'),
		'join'          => 'belongs_to_order,belongs_to_ordergoods',
		));
        
        if (!$returns_info)
		{
			$this->show_warning('没有申请记录!');
			return;
		}              
        switch ($returns_info['status'])
        {
            case '1': //申请
                $left_time = $returns_info['add_time']+$this->interval-gmtime();             
                break;
            case '3': //卖家同意退货退款
                $left_time = $returns_info['agree_time']+$this->interval-gmtime();
                $this->import_resource(array(
    			'script' => 'jquery.plugins/jquery.validate.js,jquery.plugins/additional-methods.js',
    			));
                $address_info = $this->_address_mod->get(array(
            	'fields'        => "consignee,region_name,address,zipcode,phone_tel,phone_mob",
            	'conditions'    => "addr_id={$returns_info['addr_id']} AND user_id={$returns_info['seller_id']}",
            	));
                if(!$address_info)
                {
                    $this->show_warning('卖家的退货地址不存在','重新修改申请', 'index.php?app=buyer_returns&act=edit&returns_id='.$returns_info['returns_id']);
			        return;
                }
                $this->assign('address', $address_info);               
                break;
            case '4': //卖家拒绝退货退款
                $left_time = $returns_info['refuse_time']+$this->interval-gmtime();             
                break;  
            case '5': //买家退货
                $left_time = $returns_info['shipping_time']+$this->confirm_time-gmtime();             
                break;       
            default:
                
                break;    
            
        }
		
        if($returns_info['returns_img'])
        {
            $returns_info['returns_img'] = explode('|',$returns_info['returns_img']);
        }
        if($returns_info['refuse_img'])
        {
            $returns_info['refuse_img'] = explode('|',$returns_info['refuse_img']);
        }
        $returns_info['returns_status'] = $cfg_returns['status'][$returns_info['status']][$returns_info['type']]['msg_2'];//退货退款状态提示
        $returns_info['left_time'] = $left_time;//剩余时间
        $returns_log = $this->_returns_log_mod->find(array(		
		'conditions'    => "returns_id={$returns_id} ",
        'order'         => 'log_time DESC',
		));
       // var_dump($returns_info);
        
		$this->_curlocal(LANG::get('member_center'), 'index.php?app=member',
		LANG::get('my_sales_return'), 'index.php?app=buyer_returns','退货/退款详情');

		/* 当前用户中心菜单 */
		$this->_curitem('my_sales_return');
		$this->_curmenu('returns_list');
		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_sales_return'));
		$this->assign('returns', $returns_info);
        $this->assign('returns_type_arr', $cfg_returns['type']);       
		$this->assign('returns_log',$returns_log);
		$this->display('buyer_returns.view.html');
	}
    
    /**
     *    买家申请万菱介入
     *    @author    yanghj 2014.8.11
     */
    function intervene()
	{
	   exit;
	    $returns_id = isset($_GET['returns_id']) ? intval($_GET['returns_id']) : 0;
        if(!$returns_id)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }
        $returns_data = $this->_returns_mod->get(array(
		'fields'        => "returns_id,type",
		'conditions'    => "returns_id={$returns_id} AND  buyer_id=" . $this->visitor->get('user_id'),
		));
        if(!$returns_data)
        {
            $this->show_warning('failure_error','back_index', 'index.php');
			return;
        }

        $cfg_returns = $this->_get_cfg_msg();      
	    $data = array(
		'status'    => 2,
        'finished_time'   => gmtime(),
		);
        
        /*修改退货退款状态*/
        $this->_returns_mod->edit($returns_id, $data);
        if ($this->_returns_mod->has_error())
		{
			$this->show_warning($this->_returns_mod->get_error());
			return;
		}                        
        $log_data = array(
		'returns_id' => $returns_id,
		'operator'   => $this->visitor->get('user_name'),
		'remark'     => $cfg_returns['status']['2'][$returns_data['type']]['msg_3'],
        'log_time'   => gmtime(),
		);
        
        /*添加到退货退款日志表*/
        if (!($this->_returns_log_mod->add($log_data)))
        {
            $this->show_warning($this->_returns_log_mod->get_error());    
            return;
        }
        $this->show_message('操作成功!','查看详细','index.php?app=buyer_returns&act=view&returns_id='.$returns_id);
	}



	/**
     *    获取订单中符合退货退款列表
     */
	function _get_returns()
	{
		$page = $this->_get_page(10);
		$con = array(
    		array(      //按订单号
    		'field' => 'order_sn',
            'name' => 'order_sn',
	    	'equal' => 'LIKE',
    		),
		);
		$conditions = $this->_get_query_conditions($con);
        $conditions .= " AND status in (".ORDER_ACCEPTED.",".ORDER_SHIPPED.",".ORDER_EVALUA.",".ORDER_FINISHED.") AND (finished_time > {$this->valid_time} OR finished_time=0)"; 
		/* 查找订单 */
		$orders = $this->_order_mod->findAll(array(
		'conditions'    => "buyer_id=" . $this->visitor->get('user_id') . "{$conditions}",
		'fields'        => 'this.order_sn,this.status,this.add_time,this.finished_time',
		'count'         => true,
		'limit'         => $page['limit'],
		'order'         => 'add_time DESC',
		'include'       =>  array(
		'has_ordergoods',       //取出商品
		),
		));
        
        $returns = $this->_returns_mod->find(array(
		'conditions'    => "status !=-1 AND status !=2 AND buyer_id=" . $this->visitor->get('user_id'),
		'fields'        => 'order_id,rec_id,status,type',

		));
        if($returns)
        {
            foreach($returns as $key => $val)
            {
                $temp_arr[$val['order_id']][$val['rec_id']]['returns_id'] = $val['returns_id'];
                $temp_arr[$val['order_id']][$val['rec_id']]['status'] = $val['status'];
                $temp_arr[$val['order_id']][$val['rec_id']]['type'] = $val['type'];
                
            }
        }
        
        if($orders)
        {
            foreach ($orders as $key1 => $order)
    		{
    			foreach ($order['order_goods'] as $key2 => $goods)
    			{
    			    empty($goods['goods_image']) && $orders[$key1]['order_goods'][$key2]['goods_image'] = Conf::get('default_goods_image');
    			    if(is_array($temp_arr) && isset($temp_arr[$key1][$key2]))
                    {
                        $orders[$key1]['order_goods'][$key2]['returns_id'] = $temp_arr[$key1][$key2]['returns_id'];
                        $orders[$key1]['order_goods'][$key2]['returns_status'] = $temp_arr[$key1][$key2]['status'];
                        $orders[$key1]['order_goods'][$key2]['returns_type'] = $temp_arr[$key1][$key2]['type'];
                    }   				
    			}
    		}
            
        }

		$page['item_count'] = $this->_order_mod->getCount();
		$this->assign('orders', $orders);
		$this->_format_page($page);
		$this->assign('page_info', $page);
	}
    
    /**
     * 上传图片
     *
     * @return mix false表示上传失败,空串表示没有上传,string表示上传文件地址
     */
	function _uploadify_img()
	{
	    $rs = array('state'=>false, 'msg'=>'', 'file_url'=>array());
        for($i=1;$i<6;$i++)
        {
            
            $file_src = 'file_'.$i;
            $file = $_FILES[$file_src];
            if(!isset($file))
            {
                break;                
            }
            if ($file['error'] != UPLOAD_ERR_OK)
    		{
    		    $rs['state'] = true;
    		    $rs['msg'] = '请选择上传的图片';
                return $rs;
    		}
    		import('uploader.lib');
    		$uploader = new Uploader();
    		$uploader->allowed_type(IMAGE_FILE_TYPE);
            $uploader->allowed_size(512000);
    		$uploader->addFile($file);
    		if ($uploader->file_info() === false)
    		{
    		    $rs['state'] = false;
    			$rs['msg'] = '图片的格式不对或者大小超过了500kb';
                return $rs;	
    		}
    		$uploader->root_dir(ROOT_PATH);
            $file_dir = 'data/files/returns/'.$this->visitor->get('user_id');
            $file_url = $uploader->save($file_dir, $uploader->random_filename());
            if(file_exists(ROOT_PATH.'/'.$file_url) && $file_url)
            {
                 $rs['state'] = true;
                 $rs['file_url'][] = $file_url;       
            }
            else
            { 
                 $rs['state'] = false;
                 $rs['msg'] = '上传失败';        			
            }        
        }
        return $rs;			
	}
    
    /**
     * 删除上传图片
     *
     */
	function _delete_uploadify_img($str)
	{
	   $arr = explode('|',$str);
       if(is_array($arr) && !$arr)
       {
           foreach($arr as $file)
           {
                if(file_exists(ROOT_PATH . '/' . $file))
                {
                    _at(unlink, ROOT_PATH . '/' . $file);
                }                       
           }
       } 			
	}
    
    /**
     * 生成退货退款单号:年月日时分秒+4位随机数字
     * @param int $len  长度
     */
	function _get_returns_code($len=4)
	{
		$rnd = mt_rand(("1".sprintf("%0".($len-1)."d", 0))+0,("1".sprintf("%0".$len."d", 0))-1);
		$var = sprintf("%0".$len."d", $rnd);
		return date('YmdHis').$var;
	}
    
    /**
     * 买家退货退款配置信息
     */
    function _get_cfg_msg()
    {
       //状态 0.无效 1.申请 2.取消  3.卖家同意 4.卖家拒绝  5.买家发货  6.万菱介入 7.确认 8.成功 -1.关闭
       //类型 1.退款  2.退货退款  3.换货 
        $cfg_returns = array(       
        'type' =>array(
            '1' => '退款',
            '2' => '退货退款',
            '3' => '换货',
        ),
        
        /*1.退款  2.退货退款  3.换货 原因 */
        'reason' =>array(
        '1' =>array(
            '1' => '不想要了/拍错了',
            '2' => '缺货',
            '3' => '未按约定时间发货',
            '4' => '卖家要求加价',
            '5' => '协商一致退款',
            '6' => '没有收到货',
            '7' => '包裹外包完好，配件缺失或破损',
            '8' => '包裹外包破损，导致商品破损或配件缺失',            
            '9' => '其他',
        ),
        '2' =>array(
            '1' => '商品错发/漏发/多发',
            '2' => '收到商品与描述不符',
            '3' => '商品有质量问题',
            '4' => '认为是假货',
            '5' => '不想要了/不喜欢',
            '6' => '效果不好/与期望不符',
            '7' => '找到比原商品更低价的价格',
            '8' => '包裹外包完好，配件缺失或破损',
            '9' => '包裹外包破损，导致商品破损或配件缺失',
            '10' => '其他',
        ), 
        '3' =>array(
            '1' => '收到商品与网页描述不符',
            '2' => '认为是假货',
            '3' => '包裹外包完好，配件缺失或破损',
            '4' => '包裹外包破损，导致商品破损或配件缺失',
            '5' => '其他',
        ),  
        ),
        /*1.退款  2.退货退款  3.换货 状态提示信息 */
        'status' => array(
        '0' => array(
               '1'=>array('msg_1'=>'退款关闭','msg_2'=>'退款关闭。','msg_3'=>'买家取消退款申请。'),
               '2'=>array('msg_1'=>'退货退款关闭','msg_2'=>'退货退款关闭。','msg_3'=>'买家取消退款申请。'),
               '3'=>array('msg_1'=>'退款关闭','msg_2'=>'退款关闭。','msg_3'=>'买家取消退款申请。')
         ),
        '1' => array(
               '1'=>array('msg_1'=>'退款处理中','msg_2'=>'请您等待卖家处理退款申请。','msg_3'=>'买家提交退款申请。'),
               '2'=>array('msg_1'=>'退货处理中','msg_2'=>'请您等待卖家处理退货退款申请。','msg_3'=>'买家提交退货退款申请。'),
               '3'=>array('msg_1'=>'退款处理中','msg_2'=>'请您等待卖家处理退款申请。','msg_3'=>'买家提交退款申请。')
         ),
        '2' => array(
               '1'=>array('msg_1'=>'退款关闭','msg_2'=>'退款关闭。','msg_3'=>'买家取消退款申请。'),
               '2'=>array('msg_1'=>'退货退款关闭','msg_2'=>'退货退款关闭。','msg_3'=>'买家取消退货退款申请。'),
               '3'=>array('msg_1'=>'退款关闭','msg_2'=>'退款关闭。','msg_3'=>'买家取消退款申请。')
         ),
        '3' => array(
               '1'=>array('msg_1'=>'','msg_2'=>'','msg_3'=>''),
               '2'=>array('msg_1'=>'请退货','msg_2'=>'卖家同意退货，等您发送退货商品。','msg_3'=>''),
               '3'=>array('msg_1'=>'请退货','msg_2'=>'卖家同意退货，等您发送退货商品。','msg_3'=>'')
         ),
        '4' => array(
               '1'=>array('msg_1'=>'卖家拒绝退款','msg_2'=>'卖家拒绝退款，等你处理。','msg_3'=>''),
               '2'=>array('msg_1'=>'卖家拒绝退货','msg_2'=>'卖家拒绝退货退款，等你处理。','msg_3'=>''),
               '3'=>array('msg_1'=>'请处理','msg_2'=>'卖家拒绝退款，等你处理。','msg_3'=>'')
         ),
        '5' => array(
               '1'=>array('msg_1'=>'','msg_2'=>'','msg_3'=>''),
               '2'=>array('msg_1'=>'等卖家退款','msg_2'=>'等待卖家收货并退款。','msg_3'=>'买家已发货，物流信息。'),
               '3'=>array('msg_1'=>'等卖家退款','msg_2'=>'等待卖家收货并退款。','msg_3'=>'买家已发货，物流信息。')
         ),
        '6' => array(
               '1'=>array('msg_1'=>'万菱介入中','msg_2'=>'万菱介入中','msg_3'=>'买家申请万菱介入。'),
               '2'=>array('msg_1'=>'万菱介入中','msg_2'=>'万菱介入中','msg_3'=>'买家申请万菱介入。'),
               '3'=>array('msg_1'=>'万菱介入中','msg_2'=>'万菱介入中','msg_3'=>'买家申请万菱介入。')
         ),
        '7' => array(
               '1'=>array('msg_1'=>'退款转账中','msg_2'=>'卖家同意退款。','msg_3'=>''),
               '2'=>array('msg_1'=>'退款转账中','msg_2'=>'卖家同意退款。','msg_3'=>''),
               '3'=>array('msg_1'=>'退款转账中','msg_2'=>'卖家同意退款。','msg_3'=>'')
         ),
        '8' => array(
               '1'=>array('msg_1'=>'退款成功','msg_2'=>'退款成功。','msg_3'=>'退款已成功退回买家账户。'),
               '2'=>array('msg_1'=>'退款成功','msg_2'=>'退款成功。','msg_3'=>'退款已成功退回买家账户。'),
               '3'=>array('msg_1'=>'退款成功','msg_2'=>'退款成功。','msg_3'=>'退款已成功退回买家账户。')
         ),
        '-1'=> array(
               '1'=>array('msg_1'=>'退货关闭','msg_2'=>'退货关闭。','msg_3'=>'买家超时未响应。'),
               '2'=>array('msg_1'=>'退货关闭','msg_2'=>'退货关闭。','msg_3'=>'买家超时未响应。'),
               '3'=>array('msg_1'=>'退货关闭','msg_2'=>'退货关闭。','msg_3'=>'买家超时未响应。')
         ),
        ),);
        return $cfg_returns;
    }

}

?>
